﻿CREATE PROCEDURE [dbo].[yaf_active_list](
                @BoardID INT,
                @Guests  BIT  = 0)
AS
    BEGIN
        -- delete non-active
        DELETE FROM yaf_Active
        WHERE       Datediff(MINUTE,LastActive,Getdate()) > 5
        -- select active
        IF @Guests <> 0
        SELECT   a.UserID,
                 a.Name,
                 c.IP,
                 c.SessionID,
                 c.ForumID,
                 c.TopicID,
                 ForumName = (SELECT Name
                              FROM   yaf_Forum x
                              WHERE  x.ForumID = c.ForumID),
                 TopicName = (SELECT Topic
                              FROM   yaf_Topic x
                              WHERE  x.TopicID = c.TopicID),
                 IsGuest = (SELECT 1
                            FROM   yaf_UserGroup x,
                                   yaf_Group y
                            WHERE  x.UserID = a.UserID
                            AND y.GroupID = x.GroupID
                            AND (y.Flags & 2) <> 0),
                 c.Login,
                 c.LastActive,
                 c.Location,
                 Active = Datediff(MINUTE,c.Login,c.LastActive),
                 c.Browser,
                 c.Platform
        FROM     yaf_User a,
                 yaf_Active c
        WHERE    c.UserID = a.UserID
        AND c.BoardID = @BoardID
        ORDER BY c.LastActive DESC
        ELSE
        SELECT   a.UserID,
                 a.Name,
                 c.IP,
                 c.SessionID,
                 c.ForumID,
                 c.TopicID,
                 ForumName = (SELECT Name
                              FROM   yaf_Forum x
                              WHERE  x.ForumID = c.ForumID),
                 TopicName = (SELECT Topic
                              FROM   yaf_Topic x
                              WHERE  x.TopicID = c.TopicID),
                 IsGuest = (SELECT 1
                            FROM   yaf_UserGroup x,
                                   yaf_Group y
                            WHERE  x.UserID = a.UserID
                            AND y.GroupID = x.GroupID
                            AND (y.Flags & 2) <> 0),
                 c.Login,
                 c.LastActive,
                 c.Location,
                 Active = Datediff(MINUTE,c.Login,c.LastActive),
                 c.Browser,
                 c.Platform
        FROM     yaf_User a,
                 yaf_Active c
        WHERE    c.UserID = a.UserID
        AND c.BoardID = @BoardID
        AND NOT EXISTS (SELECT 1
                        FROM   yaf_UserGroup x,
                               yaf_Group y
                        WHERE  x.UserID = a.UserID
                        AND y.GroupID = x.GroupID
                        AND (y.Flags & 2) <> 0)
        ORDER BY c.LastActive DESC
    END


